<template>
  <view>
    <view>
      <backGroundNoImg :titleName="'设备管理'" :isShowBack="isShowBack"></backGroundNoImg>
      <view v-show="isHaveDevice" class="del_container">
        <penListTab v-model:penData="penList" :btnName="'删除'" @tabpen="delPen" ></penListTab>
      </view>
      <view v-show="isNoDevice">
        <view class="fullscreen_container">
          <image class="noThing_img" src="../../images/no_offering.png" />
          <text class="noThing_text">暂无设备</text>
          <button class="add_device_btn" @click="addDevice"> + 添加设备</button>
        </view>
      </view>
    </view>

    <view v-show="dialogShow">
      <Dialog
        :dialogText="`${deviceName}${isConnect}设备${delDevieceId == state.sn?'已连接':''}，您确认要删除么?`"
        @cancel="cancelFn"
        @confrimCLick="confrimFn"
      ></Dialog>
    </view>
  </view>
</template>

<script setup>
import Taro from '@tarojs/taro';
import backGroundNoImg from '../../components/backGroundNoImg.vue';
import penListTab from '../../components/penListTab.vue';
import { ref, onMounted } from 'vue'
import Dialog from '../../components/dialog.vue';
import requset from '../../network/request'
import { getCurrentInstance } from 'vue';
import { useBluetoothStore } from '../../store/blueTooth'
  const { 
    state, 
    resetState,
    closeBLEConnection
  } = useBluetoothStore()

const instance = getCurrentInstance();
instance.appContext.config.globalProperties.$loadFontFace()

Taro.setNavigationBarColor({
  frontColor: "#000000",
  backgroundColor: '#F7F3E8'
})
const userId = Taro.getStorageSync('userId');
const userToken = Taro.getStorageSync('token');

let dialogShow = ref(false)
let deviceName = ref('')
let isConnect = ref('')
let delDevieceId = ref(0)
let isHaveDevice = ref(false)
let isNoDevice = ref(false)

let penList = ref([])
let timer = null
let isShowBack = ref(false)


onMounted(() => {
  Taro.showLoading({
    title: '加载中',
    mask: true // 是否显示透明蒙层，防止触摸穿透
  });
  timer = setTimeout(() => {
    getDeviceList()
  },500)
})

function cancelFn() {
  console.log('cancel')
  dialogShow.value = false
}

// 点击确认发送请求删除设备
function confrimFn() {
  // 重新请求数据赋值
  requset('/mini-program/device/unbind', {
    method: 'post',
    data: {
      userId,
      userToken,
      deviceId: delDevieceId
    }
  }).then(res => {
    console.log(res)
    if (res.code === 200) {

      if ( state.connected ) {
        closeBLEConnection()
      }
      console.log('清空state::::',state)
      // Taro.closeBLEConnection()
      Taro.showToast({
        title:'删除成功',
        duration: 3000
      })
      getDeviceList()
      Taro.setStorage({
        key:"isDelDeivce",
        data: true
      })
    } 
  })
  dialogShow.value = false
}

// 删除设备
function delPen(obj) {
  // console.log(obj)


  delDevieceId = obj.deviceId
  deviceName.value = obj.nickName
  dialogShow.value = true
}

// 添加设备
function addDevice() {
  // resetState()
  console.log('state.index:::', state.index)
  Taro.navigateTo({
    url: '/pages/bind/index',
  })
}

// 获取设备列表
function getDeviceList() {
  requset('/mini-program/device/list',{
    method: 'post',
    data: {
      userId,
      userToken
    }
  }).then(res => {
    Taro.hideLoading();
    clearTimeout(timer)
    const row = res.data.rows
    isShowBack.value = true
    // row.length = 0
    if (row.length) {
      const deviceId = 'F6010A0A000011'
      let newlist = row
      newlist.forEach(item => {
        if (item.deviceId === deviceId) {
          item.isConnect = true;
          item.isHave_dian = true;
          item.dian = 90
        } else {
          item.isConnect = false;
          item.isHave_dian = false;
          item.dian = 0;
        }
      });
      penList.value = newlist
      isHaveDevice.value = true
    } else {
      // 如果没有设备
      isNoDevice.value = true
      isHaveDevice.value = false
    }
  })
}

</script>

<style>
.del_container{
width: 90%;
margin: 30px auto 0 auto;
}

.fullscreen_container {
width: 240px;
height: 360px;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
text-align: center;
}

.noThing_img {
width: 216px;
height: 228px;

}

.noThing_text {
color: #816747;
font-size: 36px;
margin-top: 10px;
}

.add_device_btn{
width: 100%;
height: 80px;
line-height: 80px;
background-color: #956F31;
color: #FFF;
display: inline-block;
border-radius: 100px;
margin-top: 20px;
font-size: 34px;
}

.noDevice_con {
display: none;
}

</style>